package me.yushuai.wukong.base.config;

import me.yushuai.wukong.base.annotation.ActionLog;
import me.yushuai.wukong.base.entity.ActionLogInfo;
import me.yushuai.wukong.base.service.ActionLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 用于记录操作日志Worker
 *
 * @author zhoushuai@189.cn
 * @since 2023-09-19
 */
public class ActionLogWorker implements Runnable {

    private ActionLogService actionLogService;

    /**
     * Aop的连接点
     */
    private JoinPoint joinPoint;

    /**
     * 开始时间
     */
    private LocalDateTime startTime;

    /**
     * 结束时间
     */
    private LocalDateTime endTime;

    public ActionLogWorker(ActionLogService actionLogService, JoinPoint joinPoint, LocalDateTime startTime, LocalDateTime endTime) {
        this.actionLogService = actionLogService;
        this.joinPoint = joinPoint;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    @Override
    public void run() {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        final Object target = joinPoint.getTarget();
        final Method method = BeanUtils.findMethod(target.getClass(), methodSignature.getName(),
                methodSignature.getParameterTypes());
        assert method != null;
        final ActionLog actionLog = method.getAnnotation(ActionLog.class);

        final ActionLogInfo actionLogInfo = new ActionLogInfo();
        actionLogInfo.setMsg(actionLog.value());
        actionLogInfo.setEndTime(endTime);
        actionLogInfo.setStartTime(startTime);
        actionLogInfo.setElapsedTime(Duration.between(startTime, endTime));
        actionLogInfo.setHandlerType(target.getClass().getName());
        actionLogInfo.setHandlerMethod(methodSignature.getName());

        // 是否记录返回结果
        if (actionLog.returnValue()) {
        }

        // 是否记录参数列表
        if (actionLog.writeParams()) {

        }

        this.actionLogService.save(actionLogInfo);
    }


}
